package com.zju.searchEngine.crawler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClinetUtil {
	
	/**
	 * post请求
	 * 
	 * @param url
	 * @param data
	 * @param type
	 * @return
	 */
	public static String postReq(String url, String data, String type) {
		CloseableHttpClient client = null;
		CloseableHttpResponse resp = null;
		try {
			client = HttpClients.createDefault();
			HttpPost post = new HttpPost(url);
			post.addHeader("Content-Type", type);
			StringEntity entity = new StringEntity(data, ContentType.create(type, "utf-8"));
			post.setEntity(entity);
			resp = client.execute(post);
			int sc = resp.getStatusLine().getStatusCode();
			if (sc >= 200 && sc < 300) {
				String str = EntityUtils.toString(resp.getEntity());
				return str;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (client != null)
					client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (resp != null)
					resp.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * get请求
	 * @param url
	 * @return
	 */
	public static String sendGet(String url) {
		String content = "";
		CloseableHttpClient client = null;
		CloseableHttpResponse resp = null;
		try {
			client = HttpClients.createDefault();
			HttpGet get = new HttpGet(url);
			//get.addHeader("Content-type","application/json;charset=utf-8");
			resp = client.execute(get);
			int statusCode = resp.getStatusLine().getStatusCode();
			if (statusCode >= 200 && statusCode < 400) {
				HttpEntity entity = resp.getEntity();
				if (entity != null)
					content = EntityUtils.toString(entity,"utf-8");
			}
			return content.toString();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (resp != null)
					resp.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (client != null)
					client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
